# Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd.
# SPDX-License-Identifier: MulanPSL-2.0

import os
import sys
import logging

from logging import config as logconf
from configparser import ConfigParser

LOG_CONF = {
    "version": 1,
    "formatters": {
        "std": {
            "format": "PID=%(process)d %(asctime)s %(levelname)s : %(message)s - %(filename)s:%(lineno)d"
        },
        "simple": {
            "format": "%(asctime)s %(levelname)s : %(message)s"
        }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": "WARNING",
            "formatter": "simple",
            "stream": sys.stdout
        },
        "logfile": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "filename": "/var/log/keentune/target.log",
            "interval": 1,
            "backupCount": 14,
            "level": "INFO",
            "formatter": "std",
        }
    },
    "loggers": {
        "common": {
            "level": "INFO",
            "handlers": ["console","logfile"],
            "propagate": False
        },
        "auto": {
            "level": "DEBUG",
            "handlers": ["logfile"],
            "propagate": False
        }
    },
    "root": {
        "level": "DEBUG",
        "handlers": ["console"]
    }
}

class Config:
    conf_file_path = "/etc/keentune/target/target.conf"
    conf = ConfigParser()
    conf.read(conf_file_path)
    LOG_CONF['handlers']['console']['level']       = conf['log']['CONSOLE_LEVEL']
    LOG_CONF['handlers']['logfile']['level']       = conf['log']['LOGFILE_LEVEL']
    LOG_CONF['handlers']['logfile']['filename']    = conf['log']['LOGFILE_PATH']
    LOG_CONF['handlers']['logfile']['interval']    = int(conf['log']['LOGFILE_INTERVAL'])
    LOG_CONF['handlers']['logfile']['backupCount'] = int(conf['log']['LOGFILE_BACKUP_COUNT'])

    logconf.dictConfig(LOG_CONF)
    logger = logging.getLogger('common')

    HOME            = conf['target']['HOME']                # /etc/keentune/target
    SCRIPTS_PATH    = os.path.join(HOME, 'scripts')         # /etc/keentune/target/scripts
    WORKSPACE       = conf['target']['WORKSPACE']           # /var/keentune/target
    BACKUP_PATH     = os.path.join(WORKSPACE, "backup")     # /var/keentune/target/backup
    BENCKMARK_FIlE  = conf['target']['BENCHMARK_PATH']      # defined in keentune-bench
    TARGET_PORT     = conf['target']['TARGET_PORT']
    LIB_PATH        = "/var/keentune/lib"

    logger.info("keentune-target install path: {}".format(HOME))
    logger.info("keentune-target workspace: {}".format(WORKSPACE))
    logger.info("keentune-target listenting port: {}".format(TARGET_PORT))